"""
Data-related resources for FastMCP
"""

from fastmcp import FastMCP, Context
from datetime import datetime, timedelta
import random
import json


class DataResources:
    """Data and analytics resources for FastMCP."""

    def __init__(self, mcp: FastMCP):
        self.mcp = mcp

    def get_sample_dataset(self) -> dict:
        """Get a sample dataset for testing purposes."""
        # Generate sample data
        data_points = []
        base_date = datetime.now() - timedelta(days=30)

        for i in range(30):
            date = base_date + timedelta(days=i)
            data_points.append(
                {
                    "date": date.strftime("%Y-%m-%d"),
                    "value": round(random.uniform(10, 100), 2),
                    "category": random.choice(["A", "B", "C"]),
                    "score": random.randint(1, 10),
                }
            )

        return {
            "dataset_name": "sample_monthly_data",
            "description": "30 days of sample data with values, categories, and scores",
            "size": len(data_points),
            "data": data_points,
            "metadata": {
                "generated_at": datetime.now().isoformat(),
                "fields": {
                    "date": "Date in YYYY-MM-DD format",
                    "value": "Numeric value between 10-100",
                    "category": "Category A, B, or C",
                    "score": "Integer score between 1-10",
                },
            },
        }

    async def get_data_statistics(self, dataset: str, ctx: Context) -> dict:
        """Get statistical information about a dataset."""
        await ctx.info(f"Calculating statistics for dataset: {dataset}")

        if dataset == "sample_dataset":
            # Get the sample dataset
            sample_data = self.get_sample_dataset()
            data_points = sample_data["data"]

            # Calculate statistics
            values = [point["value"] for point in data_points]
            scores = [point["score"] for point in data_points]
            categories = [point["category"] for point in data_points]

            # Value statistics
            value_stats = {
                "count": len(values),
                "mean": round(sum(values) / len(values), 2),
                "min": min(values),
                "max": max(values),
                "median": sorted(values)[len(values) // 2],
            }

            # Score statistics
            score_stats = {
                "count": len(scores),
                "mean": round(sum(scores) / len(scores), 2),
                "min": min(scores),
                "max": max(scores),
            }

            # Category distribution
            category_counts = {}
            for cat in categories:
                category_counts[cat] = category_counts.get(cat, 0) + 1

            return {
                "dataset": dataset,
                "total_records": len(data_points),
                "value_statistics": value_stats,
                "score_statistics": score_stats,
                "category_distribution": category_counts,
                "date_range": {
                    "start": data_points[0]["date"],
                    "end": data_points[-1]["date"],
                },
                "calculated_at": datetime.now().isoformat(),
            }
        else:
            return {
                "error": f"Dataset '{dataset}' not found",
                "available_datasets": ["sample_dataset"],
                "message": "Use one of the available datasets",
            }

    def export_data(self, dataset: str, format: str) -> dict:
        """Export data in different formats."""
        if dataset == "sample_dataset":
            sample_data = self.get_sample_dataset()
            data_points = sample_data["data"]

            if format.lower() == "csv":
                # Generate CSV format
                csv_header = "date,value,category,score"
                csv_rows = [csv_header]
                for point in data_points:
                    row = f"{point['date']},{point['value']},{point['category']},{point['score']}"
                    csv_rows.append(row)

                return {
                    "dataset": dataset,
                    "format": "CSV",
                    "content": "\n".join(csv_rows),
                    "mime_type": "text/csv",
                    "size": len(csv_rows) - 1,  # Exclude header
                }

            elif format.lower() == "json":
                return {
                    "dataset": dataset,
                    "format": "JSON",
                    "content": json.dumps(data_points, indent=2),
                    "mime_type": "application/json",
                    "size": len(data_points),
                }

            elif format.lower() == "summary":
                # Create a text summary
                total_records = len(data_points)
                avg_value = sum(p["value"] for p in data_points) / total_records
                avg_score = sum(p["score"] for p in data_points) / total_records

                categories = {}
                for point in data_points:
                    cat = point["category"]
                    categories[cat] = categories.get(cat, 0) + 1

                summary = f"""Dataset Summary: {dataset}
Total Records: {total_records}
Date Range: {data_points[0]['date']} to {data_points[-1]['date']}
Average Value: {avg_value:.2f}
Average Score: {avg_score:.2f}
Category Distribution: {categories}
"""

                return {
                    "dataset": dataset,
                    "format": "Summary",
                    "content": summary,
                    "mime_type": "text/plain",
                    "size": total_records,
                }

            else:
                return {
                    "error": f"Format '{format}' not supported",
                    "supported_formats": ["csv", "json", "summary"],
                }

        else:
            return {
                "error": f"Dataset '{dataset}' not found",
                "available_datasets": ["sample_dataset"],
            }

    def get_realtime_metrics(self) -> dict:
        """Get current real-time metrics."""
        # Simulate real-time metrics
        current_time = datetime.now()

        return {
            "timestamp": current_time.isoformat(),
            "metrics": {
                "requests_per_minute": random.randint(50, 200),
                "active_connections": random.randint(10, 100),
                "response_time_ms": round(random.uniform(50, 500), 2),
                "error_rate_percent": round(random.uniform(0, 5), 2),
                "cpu_usage_percent": round(random.uniform(20, 80), 1),
                "memory_usage_percent": round(random.uniform(30, 90), 1),
            },
            "status": {
                "system": "operational",
                "database": "healthy",
                "cache": "optimal",
                "external_apis": "responding",
            },
            "alerts": {
                "critical": 0,
                "warning": random.randint(0, 3),
                "info": random.randint(0, 5),
            },
        }

    def register(self):
        """Register all data resources with FastMCP."""
        self.mcp.resource(
            uri="data://sample_dataset",
            name="Sample Dataset",
            description="A sample dataset for testing and demonstration",
            mime_type="application/json",
            tags={"data", "sample", "analytics"},
        )(self.get_sample_dataset)

        self.mcp.resource(
            uri="data://statistics/{dataset}",
            name="Data Statistics",
            description="Statistical information about available datasets",
            mime_type="application/json",
            tags={"data", "statistics", "analytics"},
        )(self.get_data_statistics)

        self.mcp.resource(
            uri="data://export/{dataset}/{format}",
            name="Data Export",
            description="Export dataset in different formats",
            tags={"data", "export", "format"},
        )(self.export_data)

        self.mcp.resource(
            uri="data://realtime/metrics",
            name="Real-time Metrics",
            description="Live metrics and performance data",
            mime_type="application/json",
            tags={"data", "realtime", "metrics", "performance"},
        )(self.get_realtime_metrics)
